package com.ikingtech.platform.business.message.service.webhook;

import com.ikingtech.framework.sdk.core.support.LogHelper;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.platform.business.message.entity.MessageSubscriberDO;
import com.ikingtech.platform.business.message.entity.MessageSubscriberSendUrlDO;
import com.ikingtech.platform.business.message.service.repository.MessageSubscriberRepository;
import com.ikingtech.platform.business.message.service.repository.MessageSubscriberSendUrlRepository;
import com.ikingtech.platform.service.push.common.Deliver;
import com.ikingtech.platform.service.push.common.DeliverResult;
import com.ikingtech.platform.service.push.common.DeliverTypeEnum;
import com.ikingtech.platform.service.push.common.PushRequest;
import lombok.RequiredArgsConstructor;

/**
 * @author tie yan
 */
@RequiredArgsConstructor
public class WebhookDeliver implements Deliver {

    private final MessageSubscriberRepository subscriberRepo;

    private final MessageSubscriberSendUrlRepository sendUrlRepo;

    @Override
    public DeliverResult send(PushRequest pushRequest, String receiverId) {
        MessageSubscriberDO subscriberEntity = this.subscriberRepo.getById(pushRequest.getAppConfigId());
        if (null == subscriberEntity) {
            LogHelper.info("WebhookDeliver", "{}[subscriberId={}]", "指定订阅方不存在", pushRequest.getAppConfigId());
            return DeliverResult.fail("subscriberNotFound");
        }
        MessageSubscriberSendUrlDO sendUrlEntity = this.sendUrlRepo.getById(pushRequest.getTemplateId());
        if (null == sendUrlEntity) {
            LogHelper.info("WebhookDeliver", "{}[subscriberId={}][sendUrlId={}]", "未配置订阅方推送地址", pushRequest.getAppConfigId(), pushRequest.getTemplateId());
            return DeliverResult.fail("subscriberSendUrlNotConfig");
        }
        try {
            String resultStr = Tools.Http.post(sendUrlEntity.getSendUrl() + "?apiKey=" + sendUrlEntity.getApiKey(), Tools.Json.toJsonStr(pushRequest.getBody()));
            if (!sendUrlEntity.getResponseValue().equals(resultStr)) {
                LogHelper.info("WebhookDeliver", "{}[cause={}][subscriberId={}][sendUrlId={}]", "推送失败", resultStr, pushRequest.getAppConfigId(), pushRequest.getTemplateId());
                return DeliverResult.fail(resultStr);
            }
        } catch (Exception e) {
            LogHelper.info("WebhookDeliver", "{}[cause={}][subscriberId={}][sendUrlId={}]", "推送异常", e.getMessage(), pushRequest.getAppConfigId(), pushRequest.getTemplateId());
            return DeliverResult.fail("subscriberSendFail");
        }
        return DeliverResult.success();
    }

    @Override
    public DeliverTypeEnum type() {
        return DeliverTypeEnum.WEBHOOK;
    }
}
